import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import { companyMenuUserTree } from '@/api/iot/iotCompanyMenuApi'

const state = {
  routes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }) {
    return new Promise(resolve => {
      companyMenuUserTree({}).then(res => {
        const { data, code } = res
        if (code === '200') {
          const accessedRoutes = []
          for (let i = 0, j = data.length; i < j; i++) {
            const menu = data[i]
            const item = {
              path: menu.path,
              name: menu.keyName,
              meta: {
                title: menu.title,
                icon: menu.icon
              }
            }
            const childrenLength = menu.children.length
            if (childrenLength > 0) {
              item.children = []
              for (let k = 0; k < childrenLength; k++) {
                const children = menu.children[k]
                item.children.push({
                  path: children.path,
                  name: children.keyName,
                  component: Layout,
                  children: [
                    {
                      path: children.path,
                      name: children.keyName,
                      component: () => require('@/pages' + children.path + '/index'),
                      meta: {
                        title: children.title,
                        icon: children.icon
                      }
                    }
                  ]
                })
              }
            }
            accessedRoutes.push(item)
          }
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })

          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
